package com.chhuang.uresource.thread;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.chhuang.core.holder.SpringContextHolder;
import com.chhuang.uresource.po.UResource;
import com.chhuang.uresource.service.IUResourceService;
import com.chhuang.utils.Assert;

public class DeleteResourceFileThread implements Runnable {
	private static final Log log = LogFactory.getLog(DeleteResourceFileThread.class);
	
	private IUResourceService resourceService = SpringContextHolder.getBean("UResourceServiceImpl");
	
	private UResource resource;
	
	public DeleteResourceFileThread(UResource uresource){
		this.resource = uresource;
	}

	@Override
	public void run() {
		if(resource==null){
			return ;
		}
		
		boolean flag = true;
		while(flag) {
			System.gc();
			sleep(2000);
			boolean deleteFileSuccess = true;
			if(Assert.isValidString(resource.getResourcePath())) {
				File file = new File(resource.getResourcePath());
				if(file.exists()) {
					deleteFileSuccess = FileUtils.deleteQuietly(file);
				}
			}
			if(deleteFileSuccess) {
				log.info("“"+resource.getResourceName()+"” 文件删除结果:" + deleteFileSuccess);
				try {
					resourceService.deleteByPrimaryKey(resource.getResourceId());
					flag = false;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	private void sleep(long ms){
		try {
			Thread.sleep(ms);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
